package easypay

import (
	"context"

	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/pay/easypay"
	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/types"
	"gitee.com/liuxuezhan/ar-platform/admin-api/pkg/xerrors/assets"
	"gitee.com/liuxuezhan/ar-platform/rpc-client/assetsClient/rpc"
	"github.com/bytedance/sonic"
	"github.com/bytedance/sonic/decoder"
	"github.com/zeromicro/go-zero/core/logc"

	"github.com/zeromicro/go-zero/core/logx"
)

type PayoutNotifyLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// easypay代付回调通知
func NewPayoutNotifyLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PayoutNotifyLogic {
	return &PayoutNotifyLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *PayoutNotifyLogic) PayoutNotify(req *types.EasyPayoutNotifyReq) (resp *types.EasyPayoutNotifyResp, err error) {
	// 回调信息转为 json 字符串
	b, _ := sonic.Marshal(req)
	logc.Info(l.ctx, string(b))
	// 获取 easypay 配置信息
	order, err := l.svcCtx.AssetsRpc.PayWithdraw.WithdrawListPage(l.ctx, &rpc.FindWithDrawReq{OrderNo: req.MerchantTradeNumber})
	if err != nil {
		return nil, err
	}
	if len(order.Data) == 0 {
		logc.Error(l.ctx, "order.Data does not exist", string(b))
		return nil, assets.ErrWithdrawPayNoChannel
	}
	if _, ok := order.Data[0].Channel[order.Data[0].WithdrawChannelId]; !ok {
		logc.Error(l.ctx, "order.Data[0].Channel[order.Data[0].WithdrawChannelId] does not exist", string(b))
		return nil, assets.ErrWithdrawPayNoChannel
	}
	// 验签
	var data map[string]any
	dc := decoder.NewDecoder(string(b))
	dc.UseNumber()
	if err = dc.Decode(&data); err != nil {
		return nil, err
	}
	sign, err := easypay.GenerateSignature(data, order.Data[0].Channel[order.Data[0].WithdrawChannelId].SecretKey)
	if err != nil {
		logc.Error(l.ctx, err)
		return nil, assets.ErrSignGenerateFailed
	}
	if sign != data["sign"] {
		logc.Error(l.ctx, "signature verification failed", string(b))
		return nil, assets.ErrSignVerifyFailed
	}
	// 根据订单状态处理业务逻辑
	switch req.OrderStatus {
	case "1":
		_, err = l.svcCtx.AssetsRpc.PayWithdraw.WithdrawSuccess(l.ctx, &rpc.SuccessWithDrawReq{OrderNo: req.MerchantTradeNumber, Data: string(b)})
		if err != nil {
			logc.Error(l.ctx, err, string(b))
			return
		}
		resp = &types.EasyPayoutNotifyResp{Ok: true}
	case "2", "3", "4":
		_, err = l.svcCtx.AssetsRpc.PayWithdraw.WithdrawFail(l.ctx, &rpc.FailWithDrawReq{OrderNo: req.MerchantTradeNumber, Data: string(b)})
		if err != nil {
			logc.Error(l.ctx, err, string(b))
			return
		}
		resp = &types.EasyPayoutNotifyResp{Ok: true}
	}
	return
}
